﻿CREATE PROCEDURE [dbo].[ListTimeEntries]
@QueryUserID INT, @UserID INT, @StartDate DATETIME, @EndDate DATETIME
AS
DECLARE @@QueryUserRoleID int

SELECT @@QueryUserRoleID = Users.RoleID FROM Users WHERE Users.UserID = @QueryUserID

IF @@QueryUserRoleID = 1 or @QueryUserID = @UserID
	BEGIN
		SELECT 
			EntryLogID, 
			EntryLog.Description, 
			Duration,
			EntryDate,
			OvernightStay,
			EntryLog.ProjectID AS ProjectID, 
			EntryLog.CategoryID AS CategoryID, 
			Categories.Name AS CategoryName, 
			Projects.Name AS ProjectName,
			ManagerUserID,  
			HasBeenBilled,
			Categories.Abbreviation AS CatShortName
		FROM 
			EntryLog 
				INNER JOIN 
				  Categories 
				ON 
				  EntryLog.CategoryID = Categories.CategoryID 
				INNER JOIN 
				  Projects 
				ON 
				  EntryLog.ProjectID = Projects.ProjectID	
		WHERE 
			UserID = @UserID 
			AND EntryDate BETWEEN @StartDate AND @EndDate
	END
ELSE IF @@QueryUserRoleID = 2
	BEGIN
		SELECT 
			EntryLogID, 
			EntryLog.Description, 
			Duration,
			OvernightStay,
			EntryDate, 
			EntryLog.ProjectID AS ProjectID, 
			EntryLog.CategoryID AS CategoryID, 
			Categories.Name AS CategoryName, 
			Projects.Name AS ProjectName,
			ManagerUserID, 
			HasBeenBilled,
			Categories.Abbreviation AS CatShortName
		FROM 
			EntryLog 
				INNER JOIN 
				  Categories 
				ON 
				  EntryLog.CategoryID = Categories.CategoryID 
				INNER JOIN 
				  Projects 
				ON 
				  EntryLog.ProjectID = Projects.ProjectID	
		WHERE 
			UserID = @UserID 
			AND EntryDate BETWEEN @StartDate AND @EndDate
			AND ManagerUserID = @QueryUserID
	END

